#!/usr/bin/env bash

# `niv update` puts base32 "nix hashes" (https://nixos.wiki/wiki/Nix_Hash) in nix/sources.json.
# These hashes can't be compared trivially with equivalent hashes output by shasum -a 256.
# This script converts the needed base32 hashes into base16 hashes that can be trivially compared.
#
# This script also makes it so there is no build-time dependency on jq (in addition to nix).
#
# Run this script when updating agent-rs, replica, ic-starter, or ic-ref in nix/sources.json.

set -e

which jq >/dev/null || ( echo "Please install jq in order to run this script." ; exit 1 )
which nix >/dev/null || ( echo "Please install nix in order to run this script." ; exit 1 )

SDK_ROOT_DIR="$( cd -- "$(dirname -- "$( dirname -- "${BASH_SOURCE[0]}" )" )" &> /dev/null && pwd )"

DFX_ASSET_SOURCES="$SDK_ROOT_DIR/scripts/dfx-asset-sources.sh"
NIX_SOURCES_JSON="$SDK_ROOT_DIR/nix/sources.json"

read_sha256_from_nix_sources() {
    KEY="$1"

    SHA256_BASE32=$(jq -r .'"'"$KEY"'".sha256' "$NIX_SOURCES_JSON")

    nix-hash --to-base16 --type sha256 "$SHA256_BASE32"
}

read_url_from_nix_sources() {
    KEY="$1"

    jq -r .'"'"$KEY"'".url' "$NIX_SOURCES_JSON"
}

normalize_varname() {
    echo "$1" | tr '[:lower:]-' '[:upper:]_'
}

write_sha256() {
    KEY="$1"
    SHA256=$(read_sha256_from_nix_sources "$KEY")

    NAME=$(normalize_varname "${KEY}_SHA256")

    echo "$NAME=\"$SHA256\"" >>"$DFX_ASSET_SOURCES"
}

write_url() {
    KEY="$1"
    URL=$(read_url_from_nix_sources "$KEY")

    NAME=$(normalize_varname "${KEY}_URL")

    echo "$NAME=\"$URL\"" >>"$DFX_ASSET_SOURCES"
}

write_var() {
    VALUE=$(jq -r .'"'"$1"'"."'"$2"'"' "$NIX_SOURCES_JSON")
    NAME=$(normalize_varname "${1}_${2}")
    echo "$NAME=\"$VALUE\"" >>"$DFX_ASSET_SOURCES"
}

echo "# generated by write-dfx-asset-sources.sh" >"$DFX_ASSET_SOURCES"

for name in "ic-ref" "ic-starter" "motoko" "replica";
do
    for platform in "darwin" "linux";
    do
        write_sha256 "${name}-x86_64-${platform}"
        write_url "${name}-x86_64-${platform}"
    done
done

write_var "icx-proxy" "branch"
write_var "icx-proxy" "rev"
write_var "icx-proxy" "repo"

write_var "motoko-base" "branch"
write_var "motoko-base" "rev"

